package com.ge.modules.api.secondController;

import com.ge.common.annotation.LoginTechnicianApi;
import com.ge.common.annotation.TechnicianAuthIgnoreApi;
import com.ge.common.utils.R;
import com.ge.common.validator.Assert;
import com.ge.modules.api.service.TbTechnicianService;
import com.ge.modules.api.service.TbTechnicianTokenService;
import com.ge.modules.entity.TbTechnicianEntity;
import com.ge.modules.entity.TbTechnicianToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * API授权登录
 *
 */
@RestController
@RequestMapping("/api/technician")
public class TbTechnicianLoginController {
    @Autowired
    private TbTechnicianService technicianService;
    @Autowired
    private TbTechnicianTokenService technicianTokenService;

    /**
     * 登录
     */
    @TechnicianAuthIgnoreApi
    @PostMapping("/login")
    public R login(String mobile, String password) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");

        //用户登录
        Integer technicianId = technicianService.login(mobile, password);

        //生成token
        Map<String, Object> map = technicianTokenService.createToken(technicianId);
        map.put("technician", technicianService.queryByTechnicianId(technicianId));
        return R.ok().put("data",map);
    }

    @RequestMapping("/loginOut")
    public R loginOut(@LoginTechnicianApi TbTechnicianEntity tbTechnician){
        Assert.isNull(tbTechnician,"技师为空");
        TbTechnicianToken technicianToken = technicianTokenService.queryByTechnicianId(tbTechnician.getTechnicianId());
        if (technicianToken!=null){
            technicianTokenService.deleteToken(technicianToken);
            return R.ok();
        }else {
            return R.error("token不能为空");
        }
    }
}
